package com.ksyun.whgc.liweiliang.work2;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.List;

/**
 * @Deseription
 * @Author lwl
 * @Date 2023/4/20 23:28
 */
public class CollectionOutputUtil {

    /**
     * @Description 根据属性的标注输出属性字段名
     * 通过反射打印 属性注解+值
     * @Author lwl
     * @Date 2023/4/20 23:47
     * @param collection
     * @return void
     */
    public static <T> void print(List<T> collection) {
        Class<?> clazz = collection.get(0).getClass();

        // 打印属性名
        for (Field field : clazz.getDeclaredFields()) {
            if (field.isAnnotationPresent(StuProperty.class)) {
                System.out.print("    "+field.getAnnotation(StuProperty.class).value());
            }
        }

        System.out.println();
        // 打印数据
        for (T item : collection) {
            System.out.print("    ");
            for (Field field : clazz.getDeclaredFields()) {
                if (field.isAnnotationPresent(StuProperty.class)) {
                    try {
                        field.setAccessible(true);
                        Object value = field.get(item);
                        System.out.print((value == null ? "" : value.toString()) + "    ");
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
            }
            System.out.println();
        }
    }


    /**
     * @Description 将String保存在文件中，为print方法服务 ---->待完善
     * @Path ../jsyun/student.txt
     * @Author lwl
     * @Date 2023/4/21 14:35
     * @param str
     * @return void
     */
    private static void writeDataToFile(String str) {

        File writefile;
        boolean append = true;
        String path = "../jsyun/student.txt";
        writefile = new File(path);
        if (writefile.exists() == false)   // 判断文件是否存在，不存在则生成
        {
            try {
                writefile.createNewFile();
                writefile = new File(path);
            } catch (IOException e) {
                // TODO 自动生成的 catch 块
                e.printStackTrace();
            }
        } else {        // 存在先删除，再创建
            writefile.delete();
            try {
                writefile.createNewFile();
                writefile = new File(path);
            } catch (IOException e) {
                // TODO 自动生成的 catch 块
                e.printStackTrace();
            }
        }
        try {
            FileWriter fw = new FileWriter(writefile, append);

            fw.write(str);
            fw.flush();
            fw.close();

        } catch (IOException e) {
            // TODO 自动生成的 catch 块
            e.printStackTrace();
        }

    }

}
